import re
import json
import logging

from django.shortcuts import render, redirect
from mac.shell import main
from django.http import HttpResponse, Http404, FileResponse
from django.db.models import Q

from mac.mac_record import mac_generate_record
from mac import models
from mac.utils import page
from mac.serializers import mac_serializer
from mac.utils import encrypt

logger = logging.getLogger(__name__)


def mac_login(request):
    '''
    登录
    :param request:
    :return:
    '''
    res = {'status': True}
    if request.method == 'GET':
        return render(request, 'login.html')
    # username = encrypt.md5(request.POST.get('username'))
    username = request.POST.get('username')
    pwd = encrypt.md5(request.POST.get('pwd'))
    # pwd = request.POST.get('pwd')
    obj = models.UserInfo.objects.filter(username=username, password=pwd).first()
    if not obj:
        res['status'] = False
        res['error'] = '用户名或密码错误,请重新输入'
        return HttpResponse(json.dumps(res))
    permission_queryset = obj.depart_id.values('jurisdiction__url',
                                                'jurisdiction__jurisdiction',
                                                'jurisdiction__is_menu')
    menu_list = []
    permission_list = []
    for item in permission_queryset:
        permission_list.append({'permission_url': item['jurisdiction__url']})
        if item['jurisdiction__is_menu']:
            menu_list.append({'title': item['jurisdiction__jurisdiction'],
                              'url': item['jurisdiction__url']})
    request.session['user_info'] = {'id': obj.id, 'name': obj.username}
    request.session['permission_list'] = permission_list
    request.session['menu_list'] = menu_list
    return HttpResponse(json.dumps(res))


def mac_logout(request):
    request.session.flush()
    return redirect('mac_login')


def mac_home(request):
    '''
    MAC首页
    :param request:
    :return:
    '''
    return render(request, 'mac_home.html')


def input_mac(request):
    '''
    输入起始MAC、数量、起始IP的表单
    :param request:
    :return:
    '''
    product_query_obj = models.Product.objects.all()
    mac_obj = models.Mac.objects.all().order_by('-id').first()
    last_id = models.Macs.objects.all().order_by('-id').first()
    if not last_id:
        return render(request, 'input_mac.html',
                      {'id': 0, 'product_obj': product_query_obj, 'mac_obj': mac_obj})
    return render(request, 'input_mac.html', {'id': last_id.id, 'product_obj': product_query_obj, 'mac_obj': mac_obj})


def generate_macs(request):
    '''
    生成MAC数据且保存到数据库中
    :param request:
    :return:
    '''
    data = {'status': True}
    future = request.POST.get('future')
    product_id = request.POST.get('product_id')
    nid = request.POST.get('id')
    mac = request.POST.get('mac')
    mac_nums = request.POST.get('mac_nums')
    ip = request.POST.get('ip')
    re_mac = re.match(r'^[0-9a-fA-F]{12}$', mac)
    re_future = re.match(r'^0x[0-9a-fA-F]+$', future)
    if ip:
        re_ip = re.match(r'((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}$', ip)
        if not re_ip:
            data['status'] = False
            data['error'] = 'ip'
            return HttpResponse(json.dumps(data))
    if not re_mac:
        data['status'] = False
        data['error'] = 'mac'
        return HttpResponse(json.dumps(data))
    if not mac_nums:
        data['status'] = False
        data['error'] = 'mac_nums'
        return HttpResponse(json.dumps(data))
    if not re_future:
        data['status'] = False
        data['error'] = 'future'
        return HttpResponse(json.dumps(data))
    next_mac, product_obj, server_error = mac_generate_record(request, mac, mac_nums, nid, product_id)
    if server_error:
        return server_error
    try:
        next_ip = main('xxx', mac, mac_nums, ip, product_obj)
    except:
        data['status'] = False
        data['error'] = 'unique'
        return HttpResponse(json.dumps(data))
    if next_ip:
        models.Product.objects.filter(id=product_id).update(address=next_ip)
    mac_obj = models.Mac.objects.filter(company_id=product_obj.company_id)
    if not mac_obj:
        models.Mac.objects.create(company_id=product_obj.company_id, mac_curr=next_mac)
    else:
        # mac_obj.mac_curr = next_mac
        # mac_obj.ip_curr = next_ip
        # mac_obj.save()
        mac_obj.update(mac_curr=next_mac)
    return HttpResponse(json.dumps(data))


def obtain_macs(request, nid, date):
    '''
    把MAC地址数据下载到本地
    :param request:
    :param nid:
    :return:
    '''

    macs_str = ''
    id_lst = nid.split('_')
    list_mac = models.Macs.objects.filter(id__gte=int(id_lst[0]), id__lte=int(id_lst[1]))
    dict_mac = list_mac.values('mac', 'uuid', 'model', 'board', 'country', 'mark', 'deviceid',
                               'secret', 'mqtt', 'private_key', 'dutpublic_key', 'public_key', 'address',
                               'endpoint_host', 'endpoint_port', 'future'
                               )
    item = list(dict_mac)[0]
    for key, value in item.items():
        if value:
            macs_str = macs_str + key + ','
    macs_str = macs_str[:-1] + '\r\n'
    for item in list(dict_mac):
        for value in item.values():
            if value:
                macs_str = macs_str + value + ','
        macs_str = macs_str[:-1] + '\r\n'
    file_name = date + '-' + dict_mac[0]['model'] + '-' + dict_mac[0]['mac'] + '-' + str(list_mac.count()) + '.csv'
    try:
        response = FileResponse(macs_str)
        response['content_type'] = "application/octet-stream"
        response['Content-Disposition'] = 'attachment; filename=' + file_name
        return response
    except Exception as e:
        logger.error(e)
        raise Http404


def download_details(request):
    '''
    展示生成MAC的全部记录
    :param request:
    :return:
    '''
    if request.method == 'POST':
        search = request.POST.get('search')
        mac_record_query = models.MacGenerateRecode.objects.filter(Q(product_name__icontains=search)
                                                                   | Q(board__icontains=search)
                                                                   | Q(user_id__fullname__icontains=search)
                                                                   ).order_by('-id')
    else:
        mac_record_query = models.MacGenerateRecode.objects.all().order_by('-id')
    mac_count = mac_record_query.count()
    pages = request.GET.get('page')
    page_size = request.GET.get('page_size')
    if not page_size:
        page_size = request.session.get('page_size', 20)
    else:
        request.session['page_size'] = request.GET.get('page_size')
    mac_record_obj = page.PageInfo(current_page=pages,
                                   all_count=mac_count,
                                   url='/download_details/',
                                   per_page=page_size)
    mac_record_page_obj = mac_record_query[mac_record_obj.start():mac_record_obj.end()]
    return render(request, 'download_details.html', {'mac_record_obj': mac_record_page_obj,
                                                     'pages': mac_record_obj.pager(),
                                                     'page_size': page_size,
                                                     'mac_count': mac_count
                                                     })


def production_plan(request):
    '''
    产品生产计划
    :param request:
    :return:
    '''
    pid = request.GET.get('pid')
    product_obj = models.Product.objects.filter(id=pid).first()
    mac_obj = models.Mac.objects.filter(company_id=product_obj.company_id).first()
    product_serializer = mac_serializer.ProductSerializer(instance=product_obj, many=False)
    macs_serializer = mac_serializer.MacsSerializer(instance=mac_obj, many=False)
    pro_mac_list = []
    pro_mac_list.append(product_serializer.data)
    pro_mac_list.append(macs_serializer.data)
    return HttpResponse(json.dumps(pro_mac_list, ensure_ascii=False))



